<?php  defined('BASEPATH') OR exit('No direct script access allowed');

class Regions extends Admin_Controller {

	/**
	 * Formatted array of all folders.
	 */
	private $_regions = array();
	private $_validation_rules = array(
		array(
			'field'	=> 'region_type',
			'label'	=> 'lang:regions.region_type',
			'rules'	=> 'required'
		),
		array(
			'field'	=> 'channel_id',
			'label'	=> 'lang:regions.channel_id',
			'rules'	=> 'required|is_natural_no_zero'
		),
		array(
			'field'	=> 'sort',
			'label'	=> 'lang:regions.sort',
			'rules'	=> 'optional|numeric'
		),
		array(
			'field'	=> 'slug',
			'label'	=> 'lang:regions.slug_label',
			'rules'	=> 'required|max_length[20]'
		),
		array(
			'field'	=> 'parent_id',
			'label'	=> 'lang:regions.parent_label',
			'rules'	=> 'required|numeric'
		),
		array(
			'field'	=> 'image',
			'label'	=> 'lang:regions.image',
			'rules'	=> 'optional|numeric'
		),
		array(
			'field'	=> 'link',
			'label'	=> 'lang:regions.link',
			'rules'	=> 'optional|max_length[100]'
		)
	);

	// ------------------------------------------------------------------------

	public function __construct()
	{
		parent::__construct();
		$this->lang->load('regions/regions');
		$this->load->config('regions');
		$this->load->model('regions/regions_model', 'regions_m');
		$this->load->library('form_validation');
		
		$supported_languages = $this->config->item('supported_languages');
		foreach($supported_languages as $language => $lang_content){
			if(CURRENT_LANGUAGE == $language){
				$rules = 'required';
			}else{
				$rules = 'optional';
			}
			$this->_validation_rules[] = array(
				'field'	=> 'name_'. $language,
				'label'	=> 'lang:regions.name_label',
				'rules'	=> $rules. '|max_length[50]'
			);
		}
		
		$this->form_validation->set_rules($this->_validation_rules);
		
		$this->_regions = $this->regions_m->get_regions();
		$regions_lang = $this->regions_m->get_lang();
		$this->lang_fields = $this->regions_m->get_lang_fields();
		
		// Get the parent -> childs
		$this->data['regions_tree'] = array();
		
		foreach($this->_regions as &$region)
		{
			$region->langs = array();
		
			$langs = array_values(array_filter($regions_lang, create_function('$row','return $row->id == "'. $region->id .'";')));
			$supported_languages = $this->config->item('supported_languages');
			foreach($supported_languages as $lang => $lang_content)
			{
				$region->langs[$lang] = array_pop(array_filter($langs, create_function('$row','return $row->lang == "'. $lang .'";')));
			}
			$this->data['regions_tree'][$region->id] = repeater('&raquo; ', $region->depth) . def_lang($region, 'name');
		}
		$this->regions_m->all_regions = $this->_regions;
		
		array_unshift($this->shortcuts, array('name' => lang('menu_2_catalog_regions'), 'link' => site_url('admin/catalog/regions')),
				array('name' => lang('menu_2_catalog_create_region'), 'link' => site_url('admin/catalog/create_region')));
		$this->template->set_data(array(
				'catalog_regions'	=> $this->_regions,
				'current_id'	=> 0,
				'shortcuts' => $this->shortcuts
		));
	}

	// ------------------------------------------------------------------------

	public function index()
	{
		$this->load->library('table');
		$quantity = 15;
		$pagination = create_pagination('admin/catalog/regions/' , count($this->_regions), $quantity, 4);

		$this->_regions = array_slice($this->_regions, ci()->uri->segment(4, 0), $quantity);
		
		$this->data['pagination'] = $pagination;
		$this->data['catalog_regions'] = $this->_regions;
		
		$this->template->load('regions/list', $this->data);
	}
	
	// ------------------------------------------------------------------------
	
	public function json()
	{
		$regions = $this->regions_m->get_lang_list(FALSE, CURRENT_LANGUAGE);
		$json_regions = array();
		foreach($regions as $region){
			$json_regions[] = array('key' => $region->id, 'value' => $region->name);
		}
		echo json_encode($json_regions);
		exit;
	}
	// ------------------------------------------------------------------------

	public function grid()
	{
		$this->template->load('regions/grid');
	}

	// ------------------------------------------------------------------------

	/**
	 * Checks if the element save process can be done.
	 *
	 * @returns		Boolean		True if the save can be done, false if not
	 *
	 */
	function _check_before_save()
	{
		$default_lang = Settings_lib::get('site_lang');
		$default_lang_name = $this->input->post('name_'.$default_lang);
	
		if ($default_lang_name == FALSE)
		{
// 			$this->session->set_flashdata('error', sprintf(lang('required'), lang('regions.name_label')));
			return FALSE;
		}
	
		return TRUE;
	}
	
	// ------------------------------------------------------------------------
	
	public function create()
	{
		if ($this->form_validation->run())
		{
			$slug = $this->input->post('slug');
			if ( count($this->regions_m->get_by('slug' , $slug)) > 0)
			{
				$message	= sprintf(lang('regions.duplicate_error'), $slug);
				$status		= 'error';			
				$this->session->set_flashdata($status, $message);
				redirect('admin/catalog/create_region');
			}
			else
			{
				if ($this->_check_before_save() == TRUE)
				{
					$id = $this->input->post('id');
					list($data, $lang_data) = $this->_prepare_data($this->regions_m->get_table());
					$data['date_added'] = time();

					$region_id = $this->regions_m->save($data, $lang_data);
					
					if($region_id){
						$message	= sprintf(lang('regions.create_success'), $slug);
						$status		= 'success';
					}else{
						$message	= sprintf(lang('regions.create_error'), $slug);
						$status		= 'error';
					}
					$this->session->set_flashdata($status, $message);
					redirect('admin/catalog/regions');
				}
			}
		}

		foreach ($this->_validation_rules as $rules)
		{
			$region->{$rules['field']} = set_value($rules['field']);
		}
		$this->data['region'] = $region;
		$this->data['region_types'] = $this->config->item('regions_type');
		$this->load->model('channels/channels_model', 'channels_m');
		$this->data['channels'] = $this->channels_m->get_lang_list(FALSE, CURRENT_LANGUAGE);
		$this->data['catalog_regions'] = $this->_regions;
		$this->template->set('site_title', lang('regions.create_title'))->load('regions/create', $this->data);
	}

	// ------------------------------------------------------------------------

	public function edit($id = 0)
	{
		$region = $this->regions_m->get($id);
		
		if ( ! $region)
		{
			redirect('admin/catalog/regions');
		}
		$region_lang = $this->regions_m->get_lang(array('id' => $id));
		$region->langs = fetch_lang($region_lang);
		
		if ($this->form_validation->run())
		{
			$slug = $this->input->post('slug');
			if ( count($this->regions_m->get_by(array('slug' => $slug, 'id <>' => $id))) > 0)
			{
				$message	= sprintf(lang('regions.duplicate_error'), $slug);
				$status		= 'error';
				// Redirect
				$this->session->set_flashdata($status, $message);
				redirect('admin/catalog/edit_region/'. $id);
			}
			else
			{
				if ($this->_check_before_save() == TRUE)
				{
					list($data, $lang_data) = $this->_prepare_data($this->regions_m->get_table());
					unset($data['date_added']);
					$region_id = $this->regions_m->save($data, $lang_data);
		
					if($region_id){
						$message	= lang('regions.edit_success');
						$status		= 'success';
					}else{
						$message	= lang('regions.edit_error');
						$status		= 'error';
					}
				}
			}
			// Redirect
			$this->session->set_flashdata($status, $message);
			redirect('admin/catalog/regions');
		}
		$this->data['region'] = $region;
		$this->data['region_types'] = $this->config->item('regions_type');
		$this->data['catalog_regions'] = $this->_regions;
		$this->load->model('channels/channels_model', 'channels_m');
		$this->data['channels'] = $this->channels_m->get_lang_list(FALSE, CURRENT_LANGUAGE);
		$this->template->set('site_title', sprintf(lang('regions.edit_title'), def_lang($region, 'name')))->load('regions/edit', $this->data);
	}

	// ------------------------------------------------------------------------

	public function delete($id = 0)
	{
		$ids = $id
			? is_array($id)
				? $id
				: array($id)
			: (array) $this->input->post('action_to');

		$total		= sizeof($ids);
		$deleted	= array();

		// Try do deletion
		foreach ($ids as $id)
		{
			// Get the row to use a value.. as title, name
			if ($region = $this->regions_m->get($id))
			{
				// Make deletion retrieving an status and store an value to display in the messages
				$deleted[($this->regions_m->delete($id) ? 'success': 'error')][] = $region->slug;
			}
		}

		// Set status messages
		foreach ($deleted as $status => &$values)
		{
			// Mass deletion
			if (($status_total = sizeof($values)) > 1)
			{
				$last_value		= array_pop($values);
				$first_values	= implode(', ', $values);

				// Success / Error message
				$values = sprintf(lang('regions.delete_mass_' . $status), $status_total, $total, $first_values, $last_value);
			}

			// Single deletion
			else
			{
				// Success / Error messages
				$values = sprintf(lang('regions.delete_' . $status), $values[0]);
			}
		}

		// He arrived here but it was not done nothing, certainly valid ids not were selected
		if ( ! $deleted)
		{
			$status		= 'error';
			$deleted	= array('error' => lang('regions.no_select_error'));
		}
		else
		{
			$status = array_key_exists('error', $deleted) ? 'error': 'success';
		}

		foreach ($deleted as $status => $message)
		{
			$this->session->set_flashdata($status, $message);
		}

		redirect('admin/catalog/regions');
	}

	// ------------------------------------------------------------------------

	public function action()
	{
		$action = strtolower($this->input->post('btnAction'));
		
		if ($action)
		{
			// Get the id('s)
			$id_array = $this->input->post('action_to');

			// Call the action we want to do
			if (method_exists($this, $action))
			{
				return $this->{$action}($id_array);
			}
		}

		redirect('admin/catalog/regions');
	}

	public function html_dropdown($id = 0)
	{
		$this->data['region'] = $id && isset($this->_regions[$id]) ? $this->_regions[$id] : array();

		return $this->load->view('admin/regions/html_dropdown', $this->data);
	}
}
